package com.zhengtoon.mctoon.conv.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class HttpXmlClient {
    private static Logger log = Logger.getLogger(HttpXmlClient.class);


    /**
     * HTTP Get请求
     *
     * @param url
     * @param paramsMap
     * @return
     * @throws Exception
     */
    public static String httpGet(String url, LinkedHashMap<String, String> paramsMap) throws IOException {
        String response = null;
        try {
            HttpClient httpClient = new HttpClient();
            HttpMethod getUrl = getMethod(url, mapConvetToString(paramsMap));
            httpClient.executeMethod(getUrl);
            if (getUrl.getStatusCode() == HttpStatus.SC_OK) {
                response = getUrl.getResponseBodyAsString();
                log.info("执行HTTP Get请求时:" + response.toString());
            }
        } catch (URIException e) {
            log.error(String.format("执行HTTP Get请求时，编码查询字符串 %s 发生异常！" + paramsMap), e);
            throw e;
        } catch (Exception e) {
            log.error(String.format("执行HTTP Get请求时异常 参数:%s,url:%s", paramsMap, url), e);
            throw e;
        }
        return response;
    }

    /**
     * map转String Get请求参数
     *
     * @param map
     * @return
     */
    public static String mapConvetToString(LinkedHashMap<String, String> map) {

        if (org.apache.commons.collections.MapUtils.isEmpty(map)) {
            throw new RuntimeException("HTTP Get请求传入参数异常");
        }
        StringBuilder params = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.append(entry.getKey());
            params.append("=" + entry.getValue());
            params.append("&");
        }
        return params.toString().substring(0, params.toString().length() - 1);
    }


    /**
     * 拼装GET请求url
     *
     * @param url
     * @param param
     * @return
     */
    private static HttpMethod getMethod(String url, String param) {

        url = url + "?" + param;
        log.info(String.format("HTTP GET 请求url:%s", url));
        GetMethod getUrl = new GetMethod(url);
        return getUrl;
    }

    /**
     * HTTP POST请求
     *
     * @param requestUrl
     * @param params
     * @return
     * @throws Exception
     */
    public static String doPost(String requestUrl, Map<String, String> params) throws Exception {
        log.info(String.format("HTTP POST 请求的url:%s  params:%s", requestUrl, params));
        String result = null;
        List<NameValuePair> nvps = buildNameValuePair(params);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(5000).build();
        try {
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.setConfig(requestConfig);
            HttpEntity httpEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
            httpPost.setEntity(httpEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            log.error("执行HTTP Post请求" + requestUrl + "时，发生异常！", e);
            throw e;
        } finally {
            httpclient.close();
        }
        return result;
    }

    /**
     * map转NameValuePair  Post请求参数
     *
     * @param params
     * @return
     */
    private static List<NameValuePair> buildNameValuePair(Map<String, String> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }

        return nvps;
    }

    /**
     * HTTP POST 请求   json格式入参
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String httpPostWithJSON(String url, Map<String, Object> params) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonValue = objectMapper.writeValueAsString(params);
        StringEntity entity = new StringEntity(jsonValue, "utf-8");//解决中文乱码问题
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        return respContent;
    }


}
